package com.sloan.community.controller;

import com.sloan.community.common.Login;
import com.sloan.community.common.query.SearchQuery;
import com.sloan.community.common.res.Result;
import com.sloan.community.common.vo.QuestionVO;
import com.sloan.community.po.User;
import com.sloan.community.service.ArticleService;
import com.sloan.community.service.QuestionService;
import com.sloan.community.service.TagService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import reactor.core.publisher.Mono;

import java.util.Objects;

@Slf4j
@Controller
@RequestMapping("question")
@RequiredArgsConstructor(onConstructor_ = {@Lazy})
public class QuestionController {

    private final QuestionService questionService;
    private final TagService tagService;

    @GetMapping("{username}/{articleId}.html")
    public Mono<String> questionDetail(@PathVariable("username") String username,
                                       @PathVariable("articleId") Long articleId,
                                       Model model, User user) {
        Mono<QuestionVO> question = questionService.questionDetail(username, articleId, user);
        return question.map(item -> {
            model.addAttribute("question", item);
            return "question";
        });
    }

    @GetMapping("tag/{tagId}.html")
    public Mono<String> list(@PathVariable("tagId") Long tagId, SearchQuery query, Model model) {
        return tagService.list(tagId, query)
                .map(article -> {
                    model.addAttribute("tag", article);
                    return "tag";
                });
    }

    @Login
    @ResponseBody
    @PutMapping("like-count/{articleId}")
    public Mono<Result<Long>> articleLikeCount(@PathVariable("articleId") Long articleId, User user) {
        Mono<Long> mono = questionService.articleLikeCount(articleId, user.getId());
        return mono.map(Result::success);
    }


    @ResponseBody
    @PutMapping("share-count/{articleId}")
    public Mono<Result<Long>> articleShareCount(@PathVariable("articleId") Long articleId) {
        Mono<Long> mono = questionService.articleShareCount(articleId);
        return mono.map(Result::success);
    }
}
